import React from "react";
import Button from "antd/lib/button";
import Col from "antd/lib/col";
import Divider from "antd/lib/divider";
import Row from "antd/lib/row";
import Radio from "antd/lib/radio";
import Select from 'antd/lib/select';
import Menu from "antd/lib/menu";
import Dropdown from "antd/lib/dropdown";
import Table from "antd/lib/table";
import ConfigProvider from "antd/lib/config-provider";
import Layout from "antd/lib/layout";
import AutoComplete from "antd/lib/auto-complete";
import zhCN from 'antd/es/locale/zh_CN';
import Payment from "@/services/payment";
import { currentUser } from "@/services/auth";
import QueryShowField from "@/services/queryshowfield";
import CreateQueryShowFieldDialog from "@/components/enums/QueryShowFieldDialog";
import { AppstoreFilled, DownOutlined, UpOutlined } from "@ant-design/icons";
import moment from "moment";
import DatePicker from "antd/lib/date-picker";
import locale from 'antd/es/date-picker/locale/zh_CN';

const getRowClassName = (record, index) => {
  let className = '';
  if (index % 2 === 0) className = "oddRow";
  return className
}

export default class PaymentunList extends React.Component {
  state = {
    page: 1,
    pagesize: localStorage.getItem("paymentunpagesize") ? (localStorage.getItem("paymentunpagesize") !== undefined ? Number(localStorage.getItem("paymentunpagesize")) : 20) : 20,
    total: 1,
    order: 1,
    loading: false,
    customername: localStorage.getItem("paymentuncustomername") ? (localStorage.getItem("paymentuncustomername") !== undefined ? localStorage.getItem("paymentuncustomername") : '') : '',
    representative: localStorage.getItem("paymentunrepresentative") ? (localStorage.getItem("paymentunrepresentative") !== undefined ? localStorage.getItem("paymentunrepresentative") : '') : '',
    code: localStorage.getItem("paymentuncode") ? (localStorage.getItem("paymentuncode") !== undefined ? localStorage.getItem("paymentuncode") : '') : '',
    name: localStorage.getItem("paymentunname") ? (localStorage.getItem("paymentunname") !== undefined ? localStorage.getItem("paymentunname") : '') : '',
    difference: "1",
    major: localStorage.getItem("paymentunmajor") ? (localStorage.getItem("paymentunmajor") !== undefined ? localStorage.getItem("paymentunmajor") : '') : '',
    area: localStorage.getItem("paymentunarea") ? (localStorage.getItem("paymentunarea") !== undefined ? localStorage.getItem("paymentunarea") : '') : '',
    bytstatus: localStorage.getItem("paymentunbytstatus") ? (localStorage.getItem("paymentunbytstatus") !== undefined ? localStorage.getItem("paymentunbytstatus") : '') : '',
    certificate: localStorage.getItem("paymentuncertificate") ? (localStorage.getItem("paymentuncertificate") !== undefined ? localStorage.getItem("paymentuncertificate") : '') : '',
    location: localStorage.getItem("paymentunlocation") ? (localStorage.getItem("paymentunlocation") !== undefined ? localStorage.getItem("paymentunlocation") : '') : '',
    payinamount:localStorage.getItem("paymentunlistpayinamount") ? (localStorage.getItem("paymentunlistpayinamount") !== undefined ? Number(localStorage.getItem("paymentunlistpayinamount")): 0) : 0,
    bill_date: [moment().startOf('year'),moment()],
    userid: currentUser.id,
    data: [],
    queryshowfielddata: [],
    showall: false,
    selectedrowkeys: '0',
  };
  componentWillMount() {

    this.fieldsshowload();
    let param = {
      page: this.state.page,
      pagesize: this.state.pagesize,
      customername: this.state.customername,
      representative: this.state.representative,
      code: this.state.code,
      name: this.state.name,
      difference: this.state.difference,
      major: this.state.major,
      area: this.state.area,
      bytstatus: this.state.bytstatus,
      certificate: this.state.certificate,
      location: this.state.location,
      userid: this.state.userid,
      paytype: this.props.paytype,
      payinamount:this.state.payinamount,
    }
    this.seldata(param);
  }
  fieldsshowload = () => {
    if (this.props.paytype === 0) {
      QueryShowField.getbycode("paymentunoutlist").then(data => {
        this.setState({
          queryshowfielddata: data,
        });
      });
    } else {
      QueryShowField.getbycode("paymentuninlist").then(data => {
        this.setState({
          queryshowfielddata: data,
        });
      });
    }
  }
  handlefieldshow = () => {
    CreateQueryShowFieldDialog.showModal({ queryshowfield: this.state.queryshowfielddata })
      .onClose((result = {}) => {
        if (result.success) {
          this.fieldsshowload();
        }
      }).onDismiss(() => {
      });
  }
  isEmptyobj = (str) => {
    if (str === '' || str === null || str === 'null' || str === undefined || str === 'undefined') {
      return true;
    } else {
      return false;
    }
  }
  seldata = (params = {}) => {
    if (!this.isEmptyobj(this.state.bill_date)) {
      if (this.state.bill_date.length === 2) {
        params.begindate = this.state.bill_date[0].format('YYYY-MM-DD');
        params.enddate = this.state.bill_date[1].format('YYYY-MM-DD');
      }
    }
    if (!currentUser.hasPermission("super_admin")) {
      params.userid = currentUser.id;
    }
    //this.setState({ loading: true });
    if (this.props.paytype === 1) {
      Payment.getuninlist(params).then(data => {
        this.setState({
          loading: false,
          data: data.data,
          page: params.page,
          pagesize: params.pagesize,
          total: data.total,
          field: params.field,
          order: params.order,
        });
      });
    } else {
      Payment.getunoutlist(params).then(data => {
        this.setState({
          loading: false,
          data: data.data,
          page: params.page,
          pagesize: params.pagesize,
          total: data.total,
          field: params.field,
          order: params.order,
        });
      });
    }

  };

  handlesel = () => {
    let param = {
      page: this.state.page,
      pagesize: this.state.pagesize,
      customername: this.state.customername,
      representative: this.state.representative,
      code: this.state.code,
      name: this.state.name,
      difference: this.state.difference,
      major: this.state.major,
      area: this.state.area,
      bytstatus: this.state.bytstatus,
      certificate: this.state.certificate,
      location: this.state.location,
      userid: this.state.userid,
      paytype: this.props.paytype,
      payinamount:this.state.payinamount,
    }
    this.seldata(param);
  };
  handleTableChange = (pagination, filters, sorter) => {
    localStorage.setItem("paymentunpagesize", pagination.pageSize);
    let field = sorter.field;
    let order = 0;
    if (sorter.order === "descend") {
      order = 1;
    }
    let param = {
      field: field,
      order: order,
      page: pagination.current,
      pagesize: this.state.pagesize,
      customername: this.state.customername,
      representative: this.state.representative,
      code: this.state.code,
      name: this.state.name,
      difference: this.state.difference,
      major: this.state.major,
      area: this.state.area,
      bytstatus: this.state.bytstatus,
      certificate: this.state.certificate,
      location: this.state.location,
      userid: this.state.userid,
      paytype: this.props.paytype,
      payinamount:this.state.payinamount,
    }
    this.seldata(param);
  };
  onDragEnter = info => {
    window.console.log(info);
  };
  handleclear = () => {
    this.setState({
      customername: "",
      representative: "",
      code: "",
      name: "",
      difference: "1",
      major: "",
      area: "",
      bytstatus: "",
      certificate: "",
      location: "",
      bill_date: [moment().startOf('year'),moment()],
      userid: currentUser.id,
    });
    localStorage.setItem("paymentuncustomername", "");
    localStorage.setItem("paymentunrepresentative", "");
    localStorage.setItem("paymentuncode", "");
    localStorage.setItem("paymentunname", "");
    localStorage.setItem("paymentunmajor", "");
    localStorage.setItem("paymentunarea", "");
    localStorage.setItem("paymentunbytstatus", "");
    localStorage.setItem("paymentuncertificate", "");
    localStorage.setItem("paymentunlocation", "");
  }
  rowSelection() {
    const _this = this;
    const props = {
      onChange(newSelectedRowKeys, newSselectedRows) {
        _this.setState({
          selectedrowkeys: newSelectedRowKeys.join(),
        });
      },
    };
    return props;
  };
  render() {
    const paginationProps = {
      showSizeChanger: true,
      total: this.state.total, // 数据总数
      pageSize: parseInt(this.state.pagesize), // 每页条数
      current: parseInt(this.state.page), // 当前页码
      pageSizeOptions: ["10", "20", "30", "100"],
      showTotal: ((total) => {
        return `共 ${total} 条`;
      }),
    };
    let listcolumns = [];
    if (this.state.queryshowfielddata.fieldsshow !== undefined) {
      (this.state.queryshowfielddata.fieldsshow || []).map(item => {
        let items = this.state.queryshowfielddata.fieldsall.filter((p) => {
          return p.key === item;
        });
        if(items.length>0){
          listcolumns.push({
            title: items[0].title,
            dataIndex: item,
            key: item,
            sorter: (a, b) => a[item] > b[item] ? 1 : -1
          })
        }
        return item;
      }
      );
    }

    // listcolumns.push({
    //   title: '操作',
    //   key: 'action',
    //   render: (record) => (
    //     <span>
    //       {(this.props.paytype === 0) && (
    //         <Button size="small">
    //           <Router history={customHistory}>
    //             <Link to={`/payment/outnew/0/${record.id}`} >付款</Link>
    //           </Router>
    //         </Button>
    //       )}
    //       {(this.props.paytype === 1) && (
    //         <Button size="small">
    //           <Router history={customHistory}>
    //             <Link to={`/payment/innew/0/${record.id}`} >收款</Link>
    //           </Router>
    //         </Button>
    //       )}
    //     </span>
    //   ),
    // });
    return (
      <ConfigProvider locale={zhCN}>
        <Layout>
          <Layout style={{ padding: '0 24px 24px' }}>
            {this.state.showall && (<><Row style={{ marginBottom: 5 }}>
              <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                人员编码:</div></Col>
              <Col span={6}>
                <AutoComplete
                  style={{ width: "100%" }}
                  value={this.state.code}
                  onChange={value => {
                    localStorage.setItem("paymentunlistcode", value);
                    this.setState({ code: value });
                  }}
                  placeholder="人员编码"
                  filterOption={(inputValue, option) =>
                    option.value.indexOf(inputValue) !== -1}>
                </AutoComplete>
              </Col>
              <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                联系人:</div></Col>
              <Col span={6}>
                <AutoComplete
                  style={{ width: "100%" }}
                  value={this.state.representative}
                  onChange={value => {
                    localStorage.setItem("paymentunlistcode", value);
                    this.setState({ representative: value });
                  }}
                  placeholder="人员编码"
                  filterOption={(inputValue, option) =>
                    option.value.indexOf(inputValue) !== -1}>
                </AutoComplete>
              </Col>
              <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
              毕业专业:</div></Col>
              <Col span={6}>
                <AutoComplete
                  style={{ width: "100%" }}
                  value={this.state.major}
                  onChange={value => {
                    localStorage.setItem("paymentunlistmajor", value);
                    this.setState({ major: value });
                  }}
                  placeholder="毕业专业"
                  filterOption={(inputValue, option) =>
                    option.value.indexOf(inputValue) !== -1}>
                </AutoComplete>
              </Col>
            </Row>
            <Row style={{ marginBottom: 5 }}>
              <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
              证书:</div></Col>
              <Col span={6}>
                <AutoComplete
                  style={{ width: "100%" }}
                  value={this.state.certificate}
                  onChange={value => {
                    localStorage.setItem("paymentuncertificate", value);
                    this.setState({ certificate: value });
                  }}
                  placeholder="证书"
                  filterOption={(inputValue, option) =>
                    option.value.indexOf(inputValue) !== -1}>
                </AutoComplete>
              </Col>
              <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
              社保地区:</div></Col>
              <Col span={6}>
                <AutoComplete
                  style={{ width: "100%" }}
                  value={this.state.area}
                  onChange={value => {
                    localStorage.setItem("paymentunlistarea", value);
                    this.setState({ area: value });
                  }}
                  placeholder="社保地区"
                  filterOption={(inputValue, option) =>
                    option.value.indexOf(inputValue) !== -1}>
                </AutoComplete>
              </Col>
              <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
              地区:</div></Col>
              <Col span={6}>
                <AutoComplete
                  style={{ width: "100%" }}
                  value={this.state.location}
                  onChange={value => {
                    localStorage.setItem("paymentunlistlocation", value);
                    this.setState({ location: value });
                  }}
                  placeholder="地区"
                  filterOption={(inputValue, option) =>
                    option.value.indexOf(inputValue) !== -1}>
                </AutoComplete>
              </Col>
              </Row>
              {this.props.paytype === 0 && ( <Row style={{ marginBottom: 5 }}>
              <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                是否收款:</div></Col>
              <Col span={6}>
                <Radio.Group onChange={e => {
                    localStorage.setItem("paymentunlistpayinamount", e.target.value);
                    this.setState({ payinamount: e.target.value });
                  }}
                  style={{ width: "100%" }}
                  value={this.state.payinamount}>
                  <Radio value={0}>所有</Radio>
                  <Radio value={1}>已收款</Radio>
                  <Radio value={2}>未收款</Radio>
                </Radio.Group>
              </Col>
            </Row>)}
            <Row style={{ marginBottom: 5 }}>
              <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                日期:</div></Col>
              <Col span={6}>
                <DatePicker.RangePicker
                  locale={locale}
                  style={{ width: "100%" }}
                  value={this.state.bill_date}
                  onChange={value => {
                    this.setState({
                      bill_date: value,
                    });
                  }}
                  autoFocus
                />
              </Col>
              {currentUser.hasPermission("super_admin") && (<><Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                录入人:</div></Col>
                <Col span={6}>
                  <Select style={{ width: "100%" }}
                    showSearch
                    allowClear
                    optionFilterProp="children"
                    value={this.state.userid}
                    onChange={value => {
                      this.setState({ userid: value });
                    }}>
                    {(this.state.employeeuserdata || []).map(item => (
                      <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
                    ))}
                  </Select>
                </Col></>)}

            </Row>
            </>)}
            <Row style={{ marginBottom: 5 }}>
            <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                单位名称:</div></Col>
              <Col span={6}>
                <AutoComplete
                  style={{ width: "100%" }}
                  value={this.state.customername}
                  onChange={value => {
                    localStorage.setItem("paymentuncustomername", value);
                    this.setState({ customername: value });
                  }}
                  placeholder="单位名称"
                  filterOption={(inputValue, option) =>
                    option.value.indexOf(inputValue) !== -1}>
                </AutoComplete>
              </Col>
              <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                人员名称:</div></Col>
              <Col span={6}>
                <AutoComplete
                  style={{ width: "100%" }}
                  value={this.state.name}
                  onChange={value => {
                    localStorage.setItem("paymentunlistname", value);
                    this.setState({ name: value });
                  }}
                  placeholder="人员名称"
                  filterOption={(inputValue, option) =>
                    option.value.indexOf(inputValue) !== -1}>
                </AutoComplete>
              </Col>
              <Col span={8}>
                <Divider type="vertical" />
                <Button type="primary" onClick={() => this.handlesel()} >
                  <i className="fa fa-search m-r-5" />
                  查询
                </Button>
                <Divider type="vertical" />
                <Button onClick={() => this.handleclear()} >
                  清空
                </Button>
                <Divider type="vertical" />
                <Button onClick={() => { this.setState({ showall: !this.state.showall }); }} >
                  {this.state.showall && (<UpOutlined />)}
                  {!this.state.showall && (<DownOutlined />)}
                  {this.state.showall ? '默认' : '更多'}
                </Button>
              </Col>
            </Row>
            <Row style={{ marginBottom: 5 }}>
              <Col span={10}>
                <Button type="primary" >
                  <i className="fa fa-plus m-r-5" />
                  {this.props.paytype === 0 && (
                    <a href={`/payment/outnew/0/${this.state.selectedrowkeys}`} style={{ color: "white" }}>付款录入</a>)}
                  {this.props.paytype === 1 && (
                    <a href={`/payment/innew/0/${this.state.selectedrowkeys}`} style={{ color: "white" }}>收款录入</a>)}
                </Button>
                <Divider type="vertical" />
                <Dropdown
                  trigger={["click"]}
                  overlay={
                    <Menu>
                      {currentUser.hasPermission("fieldshow") && (
                        <Menu.Item key="delete-item">
                          <a onMouseUp={() => this.handlefieldshow()}>显示隐藏列</a>
                        </Menu.Item>
                      )}
                    </Menu>
                  }>
                  <Button type="primary" style={{ margin: "10px" }} data-test="CreateButton" >
                    <AppstoreFilled />更多功能
                  </Button>
                </Dropdown>
              </Col>
            </Row>
            <div>
              <Table rowKey='id'
                rowClassName={(record, index) => getRowClassName(record, index)}
                rowSelection={this.rowSelection()}
                columns={listcolumns}
                scroll={{ x: 'max-content' }}
                dataSource={this.state.data}
                pagination={paginationProps}
                loading={this.state.loading}
                onChange={this.handleTableChange}
              />
            </div>
          </Layout>
        </Layout>
      </ConfigProvider>
    );
  }
}